#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import "../LockInfo/Plugin.h"

#import "FWToolbarViewCell.h"
#import "FWTransToolbar.h"
#import "FWCommon.h"
#import "FWBadgeView.h"
#import "FWApplication.h"


@implementation FWToolbarViewCell

@synthesize toolbar, label, labelIcon, badge, toolbarHeight, labelIndent, borderColor, backgroundImage;

static CGFloat const kMinToolbarHeight = 20;
static CGFloat const kToolbarIconHeight = 16;
static CGFloat const kToolbarSeparatorWidth = 2;


// ******************************************************************************************
#pragma mark -
#pragma mark Initialisation and object management

- (id)initWithFrame:(CGRect)frame table:(LITableView *)table toolbarItems:(NSArray*)navItems
{
    if (self = [super initWithFrame:CGRectZero]) {
        labelIndent = 0;
        toolbarHeight = frame.size.height;

        self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        self.contentMode = UIViewContentModeRedraw;
        self.autoresizesSubviews = YES;
        self.backgroundColor = [UIColor clearColor];
        
        FWTransToolbar* tb = [[[FWTransToolbar alloc] initWithFrame:CGRectMake(0, 0, 0, 0)] autorelease];
        tb.autoresizingMask = UIViewAutoresizingNone;
        tb.barStyle = UIBarStyleBlackTranslucent;
        tb.items = navItems;

        UIImageView* icn = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kToolbarIconHeight, kToolbarIconHeight)] autorelease];
        icn.backgroundColor = [UIColor clearColor];
        icn.image = [UIImage imageWithContentsOfFile:[[NSBundle bundleForClass:[self class]] pathForResource:@"context" ofType:@"png"]];
        icn.userInteractionEnabled = NO;
        icn.hidden = YES;
        
        LILabel* lbl = [table labelWithFrame:CGRectZero];
        lbl.frame = CGRectZero;
        lbl.style = [[table.theme.detailStyle copy] autorelease];
        lbl.backgroundColor = [UIColor clearColor];
        lbl.userInteractionEnabled = NO;
        
        FWBadgeView* bdg = [[[FWBadgeView alloc] initWithFrame:CGRectMake(0, 0, kToolbarIconHeight, frame.size.height)] autorelease];
        bdg.userInteractionEnabled = NO;

        UIImageView* iv = [[[UIImageView alloc] init] autorelease];
        
        self.toolbar = tb;
        self.label = lbl;
        self.labelIcon = icn;
        self.badge = bdg;
        self.backgroundImage = iv;

        [self addSubview:iv];
        [self addSubview:tb];
        [self addSubview:icn];
        [self addSubview:lbl];
        [self addSubview:bdg];
        
        [self setNeedsLayout];
    }

    return self;
}

- (void)dealloc
{
    [toolbar release];
    [label release];
    [labelIcon release];
    [borderColor release];
    [backgroundImage release];
    [badge release];
    
    [super dealloc];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Item layout and dimensioning

+ (CGFloat)tableView:(LITableView*)tableView heightForToolbarWithLabelStyle:(LITheme*)theme
{
    CGFloat height = theme.detailStyle.font.leading;
    if (height < kMinToolbarHeight)
        height = kMinToolbarHeight;

    return height;
}
    
- (void)layoutSubviews
{
    CGRect rect = self.superview.bounds;
    CGFloat fontHeight = label.style.font.leading;
    CGFloat labelMargin = 2;

    // Ensure that the badge is at the end of the frame
    CGSize badgeSize;
    self.badge.smallestHeight = kToolbarIconHeight;
    if (!badge.hidden)
        badgeSize = [badge sizeThatFits:CGSizeMake(0, toolbarHeight)];
    else 
        badgeSize = CGSizeZero;
    
    toolbar.frame = CGRectMake(0, 0, rect.size.width, toolbarHeight);

    if (labelIcon.hidden)
        label.frame = CGRectMake(labelIndent, 
                                 (toolbarHeight - fontHeight) / 2,
                                 rect.size.width - labelIndent - labelMargin - badgeSize.width - kToolbarSeparatorWidth,
                                 fontHeight);
    else {
        labelIcon.frame = CGRectMake(labelIndent, (toolbarHeight - kToolbarIconHeight) / 2, kToolbarIconHeight, kToolbarIconHeight);
        label.frame = CGRectMake(labelIndent + kToolbarSeparatorWidth + kToolbarIconHeight,
                                 (toolbarHeight - fontHeight) / 2,
                                 rect.size.width - labelIndent - labelMargin - badgeSize.width - kToolbarIconHeight - kToolbarSeparatorWidth,
                                 fontHeight);
    }
    
    if (!badge.hidden)
        badge.frame = CGRectMake(rect.size.width - badgeSize.width - kToolbarSeparatorWidth,
                                 (toolbarHeight - badgeSize.height) / 2,
                                 badgeSize.width,
                                 badgeSize.height);

    self.frame = CGRectMake(0, 0, rect.size.width, toolbarHeight);
    backgroundImage.frame = self.frame;
    
    // LILabel seems to stretch its text on rotation unless we do this
    [self.label setNeedsDisplay];
    
    [self setNeedsDisplay];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Drawing and updating

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    
//    CGContextRef context = UIGraphicsGetCurrentContext();
//    [self.borderColor setStroke];
//    
//    CGFloat radius = 4;
//    CGRect rrect = self.bounds;
//    
//    CGFloat minx = CGRectGetMinX(rrect);
//    CGFloat maxx = CGRectGetMaxX(rrect);
//    CGFloat miny = CGRectGetMinY(rrect);
//    CGFloat maxy = CGRectGetMaxY(rrect);
//
//    CGContextMoveToPoint(context, minx, miny);
//    CGContextAddArcToPoint(context, minx, maxy, minx + radius, maxy, radius);
//    CGContextAddArcToPoint(context, maxx, maxy, maxx, maxy - radius, radius);
//    CGContextAddLineToPoint(context, maxx, miny);
//    
//    if (!label.hidden && ([label.text length] > 0)) {
//        CGRect labelPos = label.frame;
//        if (!labelIcon.hidden)
//            labelPos = labelIcon.frame;
//        CGContextSetLineWidth(context, 2);
//        CGContextMoveToPoint(context, labelPos.origin.x - 5, miny + 2);
//        CGContextAddLineToPoint(context, labelPos.origin.x - 5, maxy - 2);
//        CGContextMoveToPoint(context, labelPos.origin.x - 5, miny + 2);
//    }        
//
//    CGContextDrawPath(context, kCGPathStroke);
}


// ******************************************************************************************
#pragma mark -
#pragma mark Attribute and information access

- (void)setInformationForTable:(LITableView *)table indent:(CGFloat)indent label:(NSString*)text;
{
    // Label should use detail style font with summary style color
    self.label.style = [[table.theme.detailStyle copy] autorelease];
    self.label.text = text;
    self.labelIcon.hidden = !([text length] > 0);

    self.toolbarHeight = [FWToolbarViewCell tableView:table heightForToolbarWithLabelStyle:table.theme];
    self.labelIndent = indent;

    self.borderColor =  table.theme.summaryStyle.textColor;

    [self setNeedsLayout];
}

- (NSArray*)items
{
    return toolbar.items;
}

- (void)setItems:(NSArray*)newItems
{
    [toolbar setItems:newItems animated:YES];
}

- (void)setBadgeValue:(NSString*)value hidden:(BOOL)hidden
{
    if (([value length] == 0) || [value isEqualToString:@"0"])
        hidden = YES;
    
    if (![badge.text isEqualToString:value] || (badge.hidden != hidden)) {
        DebugLog(@"LI:FWTodo: Badge value changed = %@", value);
        
        badge.text = value;
        badge.hidden = hidden;

        if (!hidden)
            [badge setNeedsDisplay];

        [self setNeedsLayout];
        [self setNeedsDisplay];
    }
}

- (void)setBackgroundWithImage:(UIImage*)image
{
    backgroundImage.image = image;
}

@end
